﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Word=Microsoft.Office.Interop.Word;

namespace testCreateWordFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //cria arquivo .doc
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                preencherByReplace(Application.StartupPath + "\\TesteReplace.doc");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //cria pasta para salvar os arquivos .doc
        private void Form1_Load(object sender, EventArgs e)
        {
            String termo = (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\Termos");

            if (Directory.Exists(termo))
            {
                Directory.CreateDirectory(termo);
            }
        }

        //método que substituí os valores do documento pelos valores informados.
        public void preencherByReplace(string docMatriz)
        {
            //Objeto a ser usado nos parâmetros opcionais
            object missing=System.Reflection.Missing.Value;

            //Abre a aplicação Word e faz uma cópia do documento mapeadoWord.
            Word.Application oApp = new Word.Application();

            object template = docMatriz;

            Word.Document oDoc = oApp.Documents.Add(ref template , ref missing, ref missing, ref missing);

            //Troca o conteúdo de alguns tags
            Word.Range oRng = oDoc.Range(ref missing ,ref missing );
            object FindText ="[prmCor]";
            object ReplaceWith="azul"; 
            object MatchWholeWord = true;
            object Forward = false;
            oRng.Find.Execute(ref FindText, ref missing, ref MatchWholeWord, ref missing, ref missing, ref missing, ref Forward, ref missing, ref missing, ref ReplaceWith, ref missing, ref missing, ref missing, ref missing, ref missing); 
            oRng = oDoc.Range(ref missing, ref missing);
            FindText = "[prmModelo]";
            ReplaceWith = "Pajero"; 
            oRng.Find.Execute(ref FindText, ref missing, ref MatchWholeWord, ref missing, ref missing, ref missing, ref Forward, ref missing, ref missing, ref ReplaceWith, ref missing, ref missing, ref missing, ref missing, ref missing); 
            oApp.Visible = true;
        }
    }
}
